package com.atguigu.zkb.config;

import com.atguigu.zkb.aspect.CacheAspect;
import com.atguigu.zkb.constant.CacheAbleConstant;
import com.atguigu.zkb.service.impl.CacheOpsServiceImpl;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration
@Import(CacheOpsServiceImpl.class)
public class RedissonAutoConfiguration {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedisProperties redisProperties;
    @Bean
    public RedissonClient redissonClient(){
        Config config = new Config();
        //使用useSingleServer方法指定使用单个Redis服务器。
        config.useSingleServer().setAddress(CacheAbleConstant.REDIS_CACHE_PROTOCOL + redisProperties.getHost() + CacheAbleConstant.REDIS_CACHE_PROTOCOL_SPLIT + redisProperties.getPort());
        return Redisson.create(config);
    }
    @Bean
    public RBloomFilter rBloomFilter(RedissonClient redissonClient){
        // 获取到布隆过滤器（第一次会创建一个新的 后面可以直接用）
        String bloomFilterLockKey = CacheAbleConstant.DISTRO_BLOOM_LOCK_KEY;
        //主要保证幂等性（只有第一次才能完成布隆的初始化，后面服务不管重启多少次 都不会继续初始化
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(bloomFilterLockKey, CacheAbleConstant.DISTRO_BLOOM_LOCK_FLAG);
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(CacheAbleConstant.DISTRO_BLOOM_NAME);
        if (aBoolean){
            //抢锁成功,是第一次,初始化布隆过滤器
            bloomFilter.tryInit(CacheAbleConstant.DISTRO_BLOOM_SIZE,CacheAbleConstant.DISTRO_BLOOM_FPP);
            return bloomFilter;
        }else {
            //抢锁失败,返回布隆过滤器对象
            return bloomFilter;
        }
    }
    @Bean
    public CacheAspect cacheAspect(){
       return new CacheAspect();
    }
}
